package thread.synchronized_;

public class Demo_Synchronized {
    public static void main(String[] args) throws InterruptedException {
        Printer printer = new Printer();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 500; i++) {

                    printer.print1();
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 500; i++) {
                    printer.print2();

                }
            }
        };
        t1.start();
        t1.join();
        t2.start();

    }
}
class Printer {
    Demo demo = new Demo();
    void print1() {

        synchronized(demo) {
            //同步代码块，锁对象可以是任意的,锁对象不能用匿名对象，
            //匿名对象不是同一个对象
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.print("5");
            System.out.print("6");
            System.out.print("7");
            System.out.print("8");
            System.out.print("9");
            System.out.println("\r");
        }
    }

    void print2() {
        synchronized (demo) {
            System.out.print("t1");
            System.out.print("t2");
            System.out.print("t3");
            System.out.print("t4");
            System.out.print("t5");
            System.out.print("t6");
            System.out.print("t7");
            System.out.print("t8");
            System.out.print("t9");
            System.out.println("\r");
        }
    }

}
class Demo {

}